package com.madixin.madichat.repository

import com.madixin.madichat.data.api.RetrofitClient
import com.madixin.madichat.data.model.LoginRequest
import com.madixin.madichat.util.PreferencesManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.first

class UserRepository private constructor(private val preferencesManager: PreferencesManager) {
    
    companion object {
        @Volatile
        private var INSTANCE: UserRepository? = null
        
        fun getInstance(preferencesManager: PreferencesManager): UserRepository {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: UserRepository(preferencesManager).also { INSTANCE = it }
            }
        }
    }
    
    // 添加内存中的token变量
    private val _inMemoryToken = MutableStateFlow<String?>(null)
    val inMemoryToken: StateFlow<String?> = _inMemoryToken
    
    suspend fun login(phone: String, password: String): Result<String> {
        return try {
            val response = RetrofitClient.apiService.login(LoginRequest(phone, password))
            if (response.success && response.result != null) {
                // 登录成功后，将token保存在内存中
                _inMemoryToken.value = response.result
                Result.success(response.result)
            } else {
                Result.failure(Exception(response.message.ifEmpty { "登录失败" }))
            }
        } catch (e: Exception) {
            Result.failure(Exception("网络请求失败: ${e.message}"))
        }
    }
    
    suspend fun saveToken(token: String) {
        // 保存到持久化存储
        preferencesManager.saveToken(token)
        // 同时更新内存中的token
        _inMemoryToken.value = token
    }
    
    suspend fun clearToken() {
        // 清除持久化存储中的token
        preferencesManager.clearToken()
        // 同时清除内存中的token
        _inMemoryToken.value = null
    }
    
    // 获取当前可用的token（优先使用内存中的token，如果没有则尝试从持久化存储获取）
    suspend fun getCurrentToken(): String? {
        return _inMemoryToken.value ?: preferencesManager.tokenFlow.first()
    }
}